import sys
import pygame
from Settings import Settings
from Ship import Ship
from bullet import Bullet
from alien import Alien

class AlienInvasion:
    """管理游戏资源和行为的类"""
    def __init__(self):
        #初始化游戏并创建游戏资源
        pygame.init()
        pygame.display.set_caption("Alien Invasion1")
        self.clock=pygame.time.Clock()
        self.settings=Settings()
        self.screen=pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height))
        self.bg_color=self.settings.bg_color
        self.ship=Ship(self)

        self.bullets=pygame.sprite.Group()
        self.aliens=pygame.sprite.Group()
        self._creat_fleet()

    def _creat_fleet(self):
        #创建外星舰队
        #创建一个外星人，再不断添加，直到没有空间添加外星人位置
        #外星人的间距为外星人的宽度
        alien=Alien(self)
        alien_width=alien.rect.width
        current_x=alien_width
        while current_x<(self.settings.screen_width-2*alien_width):
            self._creat_alien(current_x)
            current_x+=2*alien_width

    def _creat_alien(self,x_position):
        new_alien=Alien(self)
        new_alien.x=x_position
        new_alien.rect.x=x_position
        self.aliens.add(new_alien)

    def run_game(self):
        #开始游戏主循环
        while True:
            self._check_events()
            self.ship.update()
            self._update_bullets()
            #让最近绘制的屏幕可见
            self._update_screen()
            self.clock.tick(60)

    def _check_events(self):
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                sys.exit()
            elif event.type==pygame.KEYDOWN:
                self._check_down_events(event)
            elif event.type==pygame.KEYUP:
                self._check_up_events(event)
        
    #按下键盘
    def _check_down_events(self,event):
        if event.key==pygame.K_RIGHT:
            self.ship.moving_right=True
        elif event.key==pygame.K_LEFT:
            self.ship.moving_left=True
        elif event.key==pygame.K_SPACE:
            self._fire_bullet()
        elif event.key==pygame.K_q:
            sys.exit()

    #抬起键盘
    def _check_up_events(self,event):
        if event.key==pygame.K_RIGHT:
            self.ship.moving_right=False
        elif event.key==pygame.K_LEFT:
            self.ship.moving_left=False

    def _fire_bullet(self):
        if len(self.bullets)<self.settings.bullets_allowd:
            new_bullet= Bullet(self)
            self.bullets.add(new_bullet)

    def _update_bullets(self):
        self.bullets.update()
        for bullet in self.bullets.copy():
            if bullet.rect.bottom<=0:
                self.bullets.remove(bullet)

    def _update_screen(self):
         self.screen.fill(self.settings.bg_color)
         for bullet in self.bullets.sprites():
             bullet.draw_bullet()
         self.ship.blitme()
         self.aliens.draw(self.screen)
         pygame.display.flip()
if __name__=="__main__":
    ai=AlienInvasion()
    ai.run_game()
